import React,{useEffect,useState,useCallback} from "react";
import { useSearchParams } from 'react-router-dom'
import {  Table, Button, Popover, Popconfirm, message,Upload } from 'antd';
import { DeleteOutlined, DownloadOutlined, DoubleLeftOutlined,UploadOutlined } from '@ant-design/icons'
import request from "@/utils/request";
import AddFrom from "./AddFrom";
import ChangeItem from "./ChangeItem";
import CheckItem from "./CheckStudent";
import ChangePassword from "./ChangePassword";
import store from "../../../store";
import {host} from "@/utils/request";

function StudentsList(){
    const [userlist,setUserlist] = useState([])
    const [total,setTatal] = useState(0)
    const [rowItems,setRowItems] = useState([])
    const [search, setSearch] = useSearchParams(); 
    const [current, setCurrent] = useState({
      page: search.get('page') * 1 || 1,
      size: search.get('size') * 1 || 10
  })

   
    // 查：初始化请求数据列表
    async function userData(){
      const {data} = await request.get('/user',{
          params:{
              page:current.page,
              size:current.size,
          }
      })
      setUserlist(data.data.result)
      setTatal(data.data.total)
    }
    useEffect(()=>{
      userData()
    },[current])

   
    // 查：查看学生信息
    const checkItem = useCallback(async(item)=>{
      console.log('改',item._id)
      const {data} = await request.get(`/user/${item._id}`)
      if(data.code === 200){
        console.log(data.data)
      }
    },[])

    // 删：点击按钮获取对应id进行删除
    const confirm = useCallback(async(item) => {
      console.log('==>',item._id);
      const {data} = await request.delete(`/user/${item._id}`)
      console.log(data);
      if (data.code===204) {
        message.success('删除成功');
        userData()
      }
      
    },[userlist]) 
    
    //批量删除
    //获取已选择的id数组
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
          setRowItems(selectedRowKeys)
      }
    }
    const removeIds = useCallback(async() => {
      console.log('rowItems',rowItems)
      if(rowItems.length > 0) {
        const {data} = await request.delete('/user',{
          data:{
              ids:rowItems
          }
        })
        if (data.code===204) {
          message.success('删除成功');
          userData()
        }     
      }else{
          message.error('请勾选数据')
      }
      
    },[rowItems]) 

    // 增：点击提交添加学生
    async function addStudent(values){
      const newItem = {
          _id:parseInt(Math.random()*10000),
          username:values.username,
          class_id:values.class_id,
          phone:values.phone,
          email:values.email,
          gender:values.gender
      }
      const {data} = await request.post('/user',newItem)
      if(data.code === 201){
         setUserlist([newItem,...userlist])
      }
      
    }
    const onFinish = useCallback((FromData)=>{
        addStudent(FromData)
    },[userlist])

    //点击批量导出数据
    const handledaochu = () =>{
      const { userInfo:{_id}} = store.getState();
      if(rowItems.length === 0){
        message.error('请勾选需要导出数据')
        return
      }
      request.post('/user/export',{
            userid:_id,
            ids:rowItems,
            type:'xls'
            // type:'json'  指定json格式
      },{
      responseType:'arraybuffer',
        
      }).then(res=>{
        var blob = new Blob([res.data], {//这个里面的data 的二进制文件 创建一个文件对象
          type: 'application/vnd.ms-excel;charset=utf-8'
        })
        var downloadElement = document.createElement('a')//创建一个a 虚拟标签
        var href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download =
          decodeURI(
            res.headers['content-disposition'].split('filename=')[1]
          ) || '' // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
        message.success('导出成功')
      }).catch((res)=>{
        console.log('res',res)
      })
    }



    //点击导入
    const { userInfo:{authorization}} = store.getState()
    const props = {
      name: 'list',
      method:'post',
      action: host + '/api/user/import',
      headers: {
        authorization: authorization,
      },
    
      onChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
    
        if (info.file.status === 'done') {
          message.success(`${info.file.name}文件上传成功`);
          userData()

        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 文件上传失败`);
        }
      },
    };
    
    const pagination = {
      total,
      defaultPageSize:10,
      defaultCurrent:1,
      current:current.page,
      pageSize:current.size,
      onChange(page, size) {
        setCurrent({
            page,
            size
        })

        setSearch({
            page,
            size
        })
      }
    }

    const columns = [
      {
        title: '姓名',
        dataIndex: 'username',
      },
      {
        title: '性别',
        dataIndex: 'gender',
      },
      {
        title: '班级',
        dataIndex: 'class_id',
      },
      {
        title: '邮箱地址',
        dataIndex: 'email',
      },
      {
          title: '电话号码',
          dataIndex: 'phone',
      },
      {
        title:"操作",
        dataIndex: 'action',
        render(text, record, index){
          return <>
          <ChangeItem  changeData={record} newList={userData}/>
          <Popconfirm
            title="是否确认删除该学生信息?"
            onConfirm={()=>confirm(record)}
            okText="确认"
            cancelText="取消"
          >
          <a style={{color:'#f00',fontSize:12}}><DeleteOutlined style={{color:'#f00',marginLeft:20}} />删除</a>
          </Popconfirm>
          <Popover placement="rightTop" 
                   content={
                      <div style={{width:72}}>
                        <CheckItem CheckItem={()=>checkItem(record)} detailed={record}></CheckItem>
                        <ChangePassword passwordId={record} newList={userData}/>
                      </div>
                   }
          >
          <a style={{color:'#58bc58',fontSize:12}}><DoubleLeftOutlined style={{color:'#58bc58', marginLeft:20}} />更多</a>
          </Popover>
          </>
       }
      }
    ];

    return (
    <>
        <AddFrom  onFinish={onFinish} />
        <Popconfirm
            title="是否确认批量删除?"
            onConfirm={removeIds}
            okText="确认"
            cancelText="取消"
          >
        <Button type="primary" danger style={{marginRight:15}}><DeleteOutlined />批量删除</Button>
        </Popconfirm>
        <Button type="primary" ghost style={{marginBottom:15,marginRight:15}} onClick={handledaochu}><DownloadOutlined />导出</Button>
        <Upload {...props}>
          <Button type="primary" ghost style={{marginBottom:15}} ><UploadOutlined />导入</Button>
        </Upload>
        <Table
        rowSelection={{
            ...rowSelection,
        }}
      
        columns={columns}
        dataSource={userlist}
        rowKey={'_id'}  
        pagination={ pagination}
        />
        
    </>
    )
}

export default StudentsList